package com.example.musiccommunity.ManagerPage;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.musiccommunity.MainActivity;
import com.example.musiccommunity.R;
import com.example.musiccommunity.bean.Remark;
import com.example.musiccommunity.bean.User;
import com.example.musiccommunity.util.GridAdapter;
import com.example.musiccommunity.util.ImageUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Fragment_m_Remark#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Fragment_m_Remark extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public Fragment_m_Remark() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Fragment_m_Remark.
     */
    // TODO: Rename and change types and number of parameters
    public static Fragment_m_Remark newInstance(String param1, String param2) {
        Fragment_m_Remark fragment = new Fragment_m_Remark();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    private EditText etQuery;
    private ImageView search;


    ArrayList<Remark> remarkArrayList =new ArrayList<>();
    private GridView grid;
    BaseAdapter mAdapter = null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_m__remark, container, false);
        grid = view.findViewById(R.id.grid);

        etQuery = view.findViewById(R.id.et_query);
        search = view.findViewById(R.id.search);
        grid = view.findViewById(R.id.grid);
        //软键盘搜索
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str=etQuery.getText().toString();
                init(str);
            }
        });

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        init("");
    }
    void init(String key){
        String url= MainActivity.ip+"/remark/getAll?key="+key;
        System.out.println(url);
        StringRequest stringRequest=new StringRequest(Request.Method.POST,url, new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                //s = new String(s.getBytes("ISO-8859-1"), "UTF-8");
                //Log.d("user***********user",s.toString());
                if(s==null || s.equals("")){
                    //Toast.makeText(getContext(), "获取评论数据失败", Toast.LENGTH_SHORT).show();
                }
                else{
                    remarkArrayList =new ArrayList<>();
                    JSONObject jsonObject = null;
                    try {
                        JSONArray jsonArray = new JSONArray(s);
                        for (int i=0;i<jsonArray.length();i++){
                            jsonObject = jsonArray.getJSONObject(i);
                            String id = jsonObject.get("id").toString();
                            String img=jsonObject.get("img").toString();
                            Bitmap bit = ImageUtil.base64ToBitmap(img);
                            Remark n=new Remark(id,jsonObject.get("song_id").toString(),
                                    jsonObject.get("user").toString(),
                                    new BitmapDrawable(bit),
                                    jsonObject.get("txt").toString(),
                                    jsonObject.get("rate").toString(),
                                    jsonObject.get("like_num").toString() );
                            remarkArrayList.add(n);
                        }
                        Collections.reverse(remarkArrayList);
                        mAdapter = new GridAdapter<Remark>(remarkArrayList, R.layout.list_remark) {
                            @Override
                            public void bindView(ViewHolder holder, Remark obj) {
                                holder.setText(R.id.name, obj.getUser());
                                holder.setText(R.id.txt, obj.getTxt());
                                holder.setText(R.id.like_num, obj.getLike_num());
                                holder.setRatingBar(R.id.rating, Float.parseFloat(obj.getRate() ));
                                holder.setImageSrc(R.id.img,obj.getUser_img());
                            }

                        };
                        grid.setAdapter(mAdapter);
                        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                android.app.AlertDialog.Builder builder=new android.app.AlertDialog.Builder(getContext());
                                builder.setTitle("删除");
                                builder.setMessage("你确定要删除此评论吗？" );
                                builder.setCancelable(false);
                                String id=remarkArrayList.get(i).getId();
                                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        del(id,i);
                                    }
                                });
                                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                Dialog myDialog=builder.create();
                                myDialog.show();
                            }
                        });
                        grid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                            @Override
                            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                                return true;
                            }
                        });


                    } catch (JSONException e) {
                        System.out.println(e.toString());
                        throw new RuntimeException(e);
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("--------",volleyError.toString());
                //Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
            }
        });//字符串
        MainActivity.requestQueue.add(stringRequest);

    }

    void del(String name,int i){
        String url=MainActivity.ip+"/remark/delete?id="+name;
        System.out.println(url);
        StringRequest stringRequest=new StringRequest(Request.Method.POST,url, new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.d("user***********user",s.toString());
                if(  s.equals("success")){
                    Toast.makeText(getContext(),"删除成功",Toast.LENGTH_SHORT)
                            .show();
                    remarkArrayList.remove(i);
                    mAdapter.notifyDataSetChanged();
                }
                else{
                    Toast.makeText(getContext(), "删除失败", Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("--------",volleyError.toString());
                Toast.makeText(getContext(), "删除失败", Toast.LENGTH_SHORT).show();
            }
        });//字符串
        MainActivity.requestQueue.add(stringRequest);

    }

}